<?php
use yii\helpers\Html;
use app\models\Content;
use app\models\ContentCategory;
use app\models\TagsRelationships;
use app\models\ContentAttrRelationships;
use common\component\tool\Tool;
use common\component\tool\Pages;
use yii\db\Expression;

/*内容详情*/
function smarty_block_details($params, $content, Smarty_Internal_Template $template, &$repeat)
{
    $app_id = Yii::$app->params['app_id'];

    /*
    如果参数中存在catid，直接调取此类目的内容，说明是单页
    如果参数中有category，需要根据category，取出catid
    如果两个都存在，则忽略category
    */
    $catid = '';
    $content_id = '';
    $content_id = isset($_GET['id'])?intval($_GET['id']):$content_id;
    // if(isset($params['category'])){
    //     $res = ContentCategory::find()->select(['catid'])
    //                 ->where('alias = :alias', [':alias' => $params['category']])
    //                 ->asArray()->one();
    //     if(!is_null($res)){
    //         $catid = $res['catid'];
    //     }
    // }
    // P($catid);

    $catid = isset($params['catid'])?intval($params['catid']):$catid;
    $content_id = isset($params['id'])?intval($params['id']):$content_id;
    // P($content_id);

    if($catid or $content_id){
        if($content_id){
            $contents = Content::find()
                    ->select(['{{%content}}.content_id', '{{%content}}.catid', 'title', '{{%content}}.preview', 'source', 'author', 'describe', 'content', 'pc_preview_count', 'mobile_preview_count', 'add_time'])
                    ->where('content_id = :cid and {{%content}}.display = 2 and state = 3', [':cid' => $content_id])
                    ->joinWith('category')
                    ->asArray()->one();
            $catid = $contents['catid'];
        }else{
            $contents = Content::find()
                    ->select(['{{%content}}.content_id', '{{%content}}.catid', 'title', '{{%content}}.preview', 'source', 'author', 'describe', 'content', 'pc_preview_count', 'mobile_preview_count', 'add_time'])
                    ->where('catid = :cid and {{%content}}.display = 2 and state = 3', [':cid' => $catid])
                    // ->joinWith('category')注释原因：单页不需要上一篇、下一篇，且报错
                    ->orderBy(['content_id' => SORT_DESC])
                    ->asArray()->one();
            $content_id = $contents['content_id'];
            // P($content_id);
        }
        // P($contents);
        if(!is_null($contents)){
            if(!empty($contents['preview'])){
                $contents['preview'] = explode(',', $contents['preview']);
            }else{
                $contents['preview'] = [];
            }
            if(!empty($contents['content'])){
                $contents['content'] = Html::decode($contents['content']);
            }

            /*获取标签*/
            $tagsRelationships = TagsRelationships::find()
                        ->select('unionid, {{%tags_relationships}}.tid')
                        ->joinWith('tag')
                        ->where('{{%tags_relationships}}.app_id = :app_id and unionid = :unionid', [':app_id' => $app_id, ':unionid' => $content_id])
                        // ->createCommand()->getRawSql();
                        ->asArray()->all();
            // echo $app_id . '-' .  $content_id;
            // P($tagsRelationships);

            /*获取自定义字段*/
            $contentAttrRelationships = ContentAttrRelationships::find()
                        ->select('content_id, {{%content_attr_relationships}}.attr_id, {{%content_attr_relationships}}.attr_value')
                        ->joinWith('attrName')
                        ->where('{{%content_attr_relationships}}.app_id = :app_id and content_id = :id', [':app_id' => $app_id, ':id' => $content_id])
                        ->asArray()->all();
            foreach($contentAttrRelationships as $k => $v){
                /*多选的，需要转成数组*/
                if($v['attrName']['attr_type'] == 2 or $v['attrName']['attr_type'] == 4 or $v['attrName']['attr_type'] == 7){
                    $contentAttrRelationships[$k]['attr_value'] = json_decode($v['attr_value']);
                }
                /*编辑器，需要转义*/
                if($v['attrName']['attr_type'] == 6){
                    $contentAttrRelationships[$k]['attr_value'] = Html::decode($contentAttrRelationships[$k]['attr_value']);
                }

                /*如果是文件 注释原因：数据库已经带更目录了*/
                // if($v['attrName']['attr_type'] == 8){
                //     if(substr($contentAttrRelationships[$k]['attr_value'], 0, 4) != 'http'){
                //         $contentAttrRelationships[$k]['attr_value'] = '/' . $contentAttrRelationships[$k]['attr_value'];
                //     }
                // }

                $contentAttrRelationships[$k]['attr_name'] = $v['attrName']['attr_name'];
                unset($contentAttrRelationships[$k]['content_id']);
                unset($contentAttrRelationships[$k]['attr_id']);
                unset($contentAttrRelationships[$k]['attrName']);
            }
            // P($contentAttrRelationships);

            $isMobile = Tool::isMobile();//判断是否手机访问
            if($repeat){
                if($isMobile){//判断是否手机访问
                    Content::updateAllCounters(['mobile_preview_count' => 1], 'content_id = :id', [':id' => $content_id]);
                }else{
                    Content::updateAllCounters(['pc_preview_count' => 1], 'content_id = :id', [':id' => $content_id]);
                }
            }


            // $data = array(
            //     'content' => $content,
            //     'tags' => $tagsRelationships,
            //     'attr' => $contentAttrRelationships
            // );


            /*上一篇*/
            $prevContents = Content::find()
                    ->select(['content_id', 'title', 'preview', 'source', 'author', 'describe', 'pc_preview_count', 'mobile_preview_count', 'add_time'])
                    ->where('content_id < :cid and catid = :catid and display = 2 and state = 3', [':cid' => $content_id, ':catid' => $catid])
                    ->orderBy([
                        'istop' => SORT_DESC,
                        'toptime' => SORT_DESC,
                        'sort' => SORT_DESC,
                        'add_time' => SORT_DESC
                    ])
                    ->asArray()->one();
            /*下一篇*/
            $nextContents = Content::find()
                    ->select(['content_id', 'title', 'preview', 'describe', 'add_time'])
                    ->where('content_id > :cid and catid = :catid and display = 2 and state = 3', [':cid' => $content_id, ':catid' => $catid])
                    ->orderBy([
                        'istop' => SORT_DESC,
                        'toptime' => SORT_DESC,
                        'sort' => SORT_DESC,
                        'add_time' => SORT_DESC
                    ])
                    ->asArray()->one();
            // P($prevContents);
            if(is_null($prevContents)){
                $prevContents = [
                    'title' => '没有了！',
                    'url' => '#',
                    'preview' => '',
                    'describe' => '',
                    'add_time' => '',
                ];
            }else{
                $prevContents['url'] = '/' . $contents['category']['alias'] . '/article/' . $prevContents['content_id'];
            };
            if(is_null($nextContents)){
                $nextContents = [
                    'title' => '没有了！',
                    'url' => '#',
                    'preview' => '',
                    'describe' => '',
                    'add_time' => '',
                ];
            }else{
                $nextContents['url'] = '/' . $contents['category']['alias'] . '/article/' . $nextContents['content_id'];
            }
            // P($nextContents);


            $template->assign("title", $contents['title']);
            $template->assign("source", $contents['source']);
            $template->assign("author", $contents['author']);
            $template->assign("preview", $contents['preview']);
            $template->assign("describe", $contents['describe']);
            $template->assign("main_content", $contents['content']);
            $template->assign("pc_count", $contents['pc_preview_count'] + 1);
            $template->assign("mobile_count", $contents['mobile_preview_count'] + 1);
            $template->assign("add_time", $contents['add_time']);
            $template->assign("tags", $tagsRelationships);
            $template->assign("attr", $contentAttrRelationships);
            $template->assign("prev", $prevContents);
            $template->assign("next", $nextContents);
            // P($contents);
        }else{
            // $data = array(
            //     'content' => [],
            //     'tags' => [],
            //     'attr' => []
            // );
            $template->assign("title", '');
            $template->assign("source", '');
            $template->assign("author", '');
            $template->assign("preview", []);
            $template->assign("describe", '');
            $template->assign("main_content", '');
            $template->assign("pc_count", 0);
            $template->assign("mobile_count", 0);
            $template->assign("add_time", '');
            $template->assign("tags", []);
            $template->assign("attr", []);
            $template->assign("prev", []);
            $template->assign("next", []);
        };
    }else{
        $template->assign("title", '');
        $template->assign("source", '');
        $template->assign("author", '');
        $template->assign("preview", []);
        $template->assign("describe", '');
        $template->assign("main_content", '');
        $template->assign("pc_count", 0);
        $template->assign("mobile_count", 0);
        $template->assign("add_time", '');
        $template->assign("tags", []);
        $template->assign("attr", []);
        $template->assign("prev", []);
        $template->assign("next", []);
    }
    // P($contents);


    
    
    return $content;

}